<template>
  <header class="app-header">
    <div class="header-content">
      <div class="left-section">
        <div class="logo-container">
          <h1 class="logo">Noody</h1>
          <img src="../assets/noody-logo.svg" alt="Noody Logo" class="logo-image" />
        </div>
      </div>
      
      <div class="center-section">
        <nav class="main-nav">
          <ul>
            <li><router-link to="/" class="nav-link" active-class="active">首页</router-link></li>
            <li><router-link to="/anime" class="nav-link" active-class="active">番剧</router-link></li>
            <li><router-link to="/games" class="nav-link" active-class="active">游戏中心</router-link></li>
            <li><router-link to="/shop" class="nav-link" active-class="active">会员购</router-link></li>
            <li><router-link to="/comics" class="nav-link" active-class="active">漫画</router-link></li>
            <li><router-link to="/events" class="nav-link" active-class="active">赛事</router-link></li>
          </ul>
        </nav>
      </div>
      
      <div class="right-section">
        <div class="user-actions">
          <!-- 搜索框 -->
          <div class="search-box">
            <input 
              type="text" 
              :placeholder="searchPlaceholder || '搜索...'" 
              v-model="localSearchQuery"
              @input="$emit('search-change', localSearchQuery)"
              @keypress.enter="$emit('search', localSearchQuery)"
            />
            <button class="search-button" @click="$emit('search', localSearchQuery)">🔍</button>
          </div>
          
          <!-- 购物车按钮（仅在shop页面显示） -->
          <button v-if="showCart" class="cart-button" @click="$emit('open-cart')">
            <span class="icon">🛒</span>
            <span class="badge" v-if="cartCount > 0">{{ cartCount }}</span>
          </button>
          
          <!-- 消息通知 -->
          <router-link to="/messages" class="notification-button">
            <span class="icon">🔔</span>
            <span class="badge" v-if="unreadCount > 0">{{ unreadCount }}</span>
          </router-link>
          
          <!-- 根据登录状态显示不同内容 -->
          <div v-if="userStore.isLoggedIn" class="user-profile" @click="toggleUserMenu">
            <img 
              :src="userStore.user?.avatar || 'https://picsum.photos/id/1005/200/200'" 
              alt="用户头像" 
              class="avatar"
            />
            <span class="username">{{ userStore.user?.nickname || '用户' }}</span>
            <span class="vip-badge" v-if="userStore.user?.isVip">VIP</span>
            <span class="dropdown-icon">{{ userMenuOpen ? '▼' : '▲' }}</span>
          </div>
          <div v-else>
            <router-link to="/login" class="login-button-small">登录</router-link>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 用户下拉菜单 -->
    <div class="user-dropdown" v-show="userMenuOpen" ref="dropdownRef">
      <ul>
        <li><router-link to="/profile" @click="userMenuOpen = false">个人主页</router-link></li>
        <li><router-link to="/messages" @click="userMenuOpen = false">消息中心</router-link></li>
        <li><a href="#">设置</a></li>
        <li><a href="#" @click="handleLogout">退出登录</a></li>
      </ul>
    </div>
  </header>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'

// 定义组件属性
const props = defineProps({
  showCart: {
    type: Boolean,
    default: false
  },
  cartCount: {
    type: Number,
    default: 0
  },
  searchPlaceholder: {
    type: String,
    default: '搜索视频、番剧、用户...'
  }
})

// 定义事件
const emit = defineEmits(['search', 'search-change', 'open-cart'])

const router = useRouter()
const userStore = useUserStore()
const userMenuOpen = ref(false)
const dropdownRef = ref(null)

// 消息数据 - 与MessagesView.vue保持一致
const systemMessages = ref([
  { id: 1, content: '恭喜您获得了创作者认证资格，点击查看详情。', time: '今天 10:30', read: false },
  { id: 2, content: '系统将于6月1日凌晨2点进行维护，预计持续2小时。', time: '昨天 18:30', read: false },
  { id: 3, content: '您的账户已成功升级为会员，享受更多特权！', time: '3天前', read: true }
])

const commentsMessages = ref([
  { id: 1, content: '非常喜欢你的视频，学到了很多东西！', time: '昨天 15:45', read: false, sender: '学习达人' },
  { id: 2, content: '@用户 这个问题你怎么看？', time: '昨天 10:20', read: true, sender: '讨论组组长' }
])

const purchaseMessages = ref([
  { id: 1, content: '您的订单已发货，点击查看物流信息。', time: '今天 12:30', read: false },
  { id: 2, content: '您的会员已成功开通，有效期至2025年5月20日。', time: '昨天 09:15', read: false },
  { id: 3, content: '您的购买已完成，感谢您的支持！', time: '3天前', read: true }
])

const privateChats = ref([
  { id: 1, name: '小明同学', avatar: 'https://picsum.photos/id/1012/200/200', lastMessage: '你好，我想请教一个关于视频制作的问题', lastTime: '3天前', unread: 1 },
  { id: 2, name: '技术讨论组', avatar: 'https://picsum.photos/id/1013/200/200', lastMessage: '每周技术分享活动即将开始，记得参加！', lastTime: '上周', unread: 0 },
  { id: 3, name: '创意团队', avatar: 'https://picsum.photos/id/1014/200/200', lastMessage: '关于下一个项目，我们有新的想法想和你讨论', lastTime: '2周前', unread: 0 }
])

// 计算未读消息数量 - 与MessagesView.vue保持一致
const systemUnread = computed(() => {
  return systemMessages.value.filter(msg => !msg.read).length
})

const commentsUnread = computed(() => {
  return commentsMessages.value.filter(msg => !msg.read).length
})

const purchaseUnread = computed(() => {
  return purchaseMessages.value.filter(msg => !msg.read).length
})

const privateUnread = computed(() => {
  return privateChats.value.reduce((sum, chat) => sum + chat.unread, 0)
})

const unreadCount = computed(() => {
  return systemUnread.value + commentsUnread.value + purchaseUnread.value + privateUnread.value
})

const localSearchQuery = ref('')

// 切换用户下拉菜单
const toggleUserMenu = () => {
  userMenuOpen.value = !userMenuOpen.value
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  router.push('/')
  userMenuOpen.value = false
}

// 点击页面其他地方关闭下拉菜单
const handleClickOutside = (event) => {
  if (dropdownRef.value && !dropdownRef.value.contains(event.target)) {
    const userProfile = event.target.closest('.user-profile')
    if (!userProfile) {
      userMenuOpen.value = false
    }
  }
}

// 从localStorage加载消息状态 - 与MessagesView.vue保持一致
const loadMessageStates = () => {
  try {
    const savedStates = localStorage.getItem('messageStates')
    if (savedStates) {
      const states = JSON.parse(savedStates)
      // 恢复系统消息状态
      if (states.systemMessages) {
        states.systemMessages.forEach(savedMsg => {
          const msg = systemMessages.value.find(m => m.id === savedMsg.id)
          if (msg) msg.read = savedMsg.read
        })
      }
      // 恢复评论消息状态
      if (states.commentsMessages) {
        states.commentsMessages.forEach(savedMsg => {
          const msg = commentsMessages.value.find(m => m.id === savedMsg.id)
          if (msg) msg.read = savedMsg.read
        })
      }
      // 恢复购买消息状态
      if (states.purchaseMessages) {
        states.purchaseMessages.forEach(savedMsg => {
          const msg = purchaseMessages.value.find(m => m.id === savedMsg.id)
          if (msg) msg.read = savedMsg.read
        })
      }
      // 恢复私信状态
      if (states.privateChats) {
        states.privateChats.forEach(savedChat => {
          const chat = privateChats.value.find(c => c.id === savedChat.id)
          if (chat) chat.unread = savedChat.unread
        })
      }
    }
  } catch (error) {
    console.error('加载消息状态失败:', error)
  }
}

// 初始化时加载用户信息和消息状态
onMounted(() => {
  window.addEventListener('click', handleClickOutside)
  userStore.loadUser()
  loadMessageStates() // 加载保存的消息状态
})

onUnmounted(() => {
  window.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.app-header {
  background-color: #ffffff;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
    width: 100%;
    max-width: 1200px;
    padding: 0 20px;
    display: flex;
    align-items: center;
    height: 60px;
    box-sizing: border-box;
    margin: 0 auto;
  }

  .left-section {
    flex-shrink: 0;
    min-width: 150px; /* 给左侧固定宽度 */
  }

  .center-section {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    min-width: 0;
  }

  .right-section {
    flex-shrink: 0;
    min-width: 300px; /* 给右侧固定宽度 */
    display: flex;
    justify-content: flex-end;
  }

  .logo-container {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .logo {
    font-size: 24px;
    font-weight: bold;
    color: #4CAF50;
    margin: 0;
  }

  .logo-image {
    height: 30px;
  }

  .main-nav {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .main-nav ul {
    display: flex;
    list-style: none;
    justify-content: center;
    margin: 0;
    padding: 0;
  }

  .main-nav li {
    margin: 0 15px;
    white-space: nowrap;
  }

  .nav-link {
    text-decoration: none;
    color: #333;
    font-size: 14px;
    font-weight: 500;
    padding: 5px 0;
    position: relative;
    display: inline-block;
  }

.nav-link:hover,
.nav-link.active {
  color: #4CAF50;
}

.nav-link.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: #4CAF50;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-box {
  display: flex;
  align-items: center;
  position: relative;
}

.search-box input {
  width: 200px;
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
}

.search-button {
  position: absolute;
  right: 6px;
  background: none;
  border: none;
  cursor: pointer;
  color: #666;
}

.notification-button,
.cart-button {
  position: relative;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 20px;
  text-decoration: none;
  color: inherit;
}

.badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color:rgb(0, 255, 106);
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 18px;
  text-align: center;
}

.vip-badge {
  background-color: #ffd700;
  color: #333;
  font-size: 11px;
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: 5px;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.user-profile:hover {
  background-color: #f5f5f5;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.username {
  font-size: 14px;
  font-weight: 500;
}

.dropdown-icon {
  font-size: 12px;
  color: #666;
}

.login-button-small {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  text-decoration: none;
  transition: background-color 0.3s ease;
}

.login-button-small:hover {
  background-color: #45a049;
}

.user-dropdown {
  position: absolute;
  top: 100%;
  right: 20px;
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 200px;
  margin-top: 8px;
}

.user-dropdown ul {
  list-style: none;
  margin: 0;
  padding: 8px 0;
}

.user-dropdown li {
  padding: 0;
}

.user-dropdown a {
  display: block;
  padding: 12px 20px;
  text-decoration: none;
  color: #333;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.user-dropdown a:hover {
  background-color: #f5f5f5;
}
</style>